'''
Created on Jun 27, 2012

@author: thomas_dao
'''

import urls, util
import webapp2
import csv
import logging
from entity import Recipe, Tag
from google.appengine.ext import ndb

@ndb.tasklet
def import_data():
    with open('Recipes.csv', 'rU') as f:
        count = yield Tag.query().count_async(limit=2)
        if count==0:
            reader = csv.reader(f)
            for row in reader:
                title = row[0]
                text = row[1]
                recipe = Recipe()
                recipe.title = title
                recipe.recipe = text
                logging.info(recipe.recipe)
                
                tag_keys = []
                tags = row[2]
                tags = tags.split(',')
                for tag in tags:
                    if tag != "" and tag != " ":
                        tag = tag.strip()
                        new_tag = yield Tag.get_or_insert_async(tag, tag=tag)
                        tag_keys.append(new_tag.key)
                    
                recipe.tags = tag_keys
                yield recipe.put_async()            
        else:
            pass
        
        raise ndb.Return()
            

class ImportDataHandler(webapp2.RequestHandler):
    @ndb.synctasklet
    def get(self):
        yield import_data()
        template = util.jinja_environment().get_template('import-data.html')
        self.response.out.write(template.render({}))    

class DeleteDataHandler(webapp2.RequestHandler):
    def post(self):
        tag_keys = Tag.query().fetch(keys_only=True)
        recipe_keys = Recipe.query().fetch(keys_only=True)
        ndb.delete_multi(tag_keys + recipe_keys)
        self.response.out.write("Done")   
        
app = urls.app




def main():
    app.run()

if __name__ == '__main__':
    main()